package com.letfox.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

public class MD5Util {

    public final static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获得MD5加密字符串
     *
     * @param source 源字符串
     * @return 加密后的字符串
     */
    public static String getMD5ForChinese(String source) {

        String mdString = null;

        if (source != null) {

            try {

                mdString = getMD5(source.getBytes("UTF-8"));

            } catch (UnsupportedEncodingException e) {

                e.printStackTrace();

            }

        }

        return mdString;

    }


    /**
     * 获得MD5加密字符串
     *
     * @param source 源字节数组
     * @return 加密后的字符串
     */
    public static String getMD5(byte[] source) {

        String s = null;

        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',

                '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        final int temp = 0xf;

        final int arraySize = 32;

        final int strLen = 16;

        final int offset = 4;

        try {

            java.security.MessageDigest md = java.security.MessageDigest

                    .getInstance("MD5");

            md.update(source);

            byte[] tmp = md.digest();

            char[] str = new char[arraySize];

            int k = 0;

            for (int i = 0; i < strLen; i++) {

                byte byte0 = tmp[i];

                str[k++] = hexDigits[byte0 >>> offset & temp];

                str[k++] = hexDigits[byte0 & temp];

            }

            s = new String(str);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return s;

    }

    public static void main(String[] args) {
        System.out.println(MD5Util.MD5("123456"));
        System.out.println("e10adc3949ba59abbe56e057f20f883e");
        System.out.println(MD5Util.MD5("123456").equals("e10adc3949ba59abbe56e057f20f883e"));
        System.out.println(MD5Util.MD5("加密"));
    }

}
